// 路由鉴权设置 (进度条设置和路由组件访问权限设置)
import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from '@/store'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore(pinia)
// console.log(userStore.token)

// 全局守卫: 路由切换就触发的钩子
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  nprogress.start()
  const token: any = userStore.token
  const username = userStore.username
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 判断是否获取到了用户信息（信息会在刷新之后消失）
      if (username) {
        next()
      } else {
        try {
          await userStore.userInfo()
          next()
        } catch (err) {
          //token过期的情况
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    //未登录判断
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

//全局后置守卫
router.afterEach((to, from) => {
  nprogress.done()

  document.title = (to.meta.title as string) || ' '
})
